import 'package:get/get.dart';
import 'package:mokeng/utils/utils.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class TransController extends GetxController {
  final newsList = [].obs;

  /// UI 组件
  final RefreshController refreshController = RefreshController(
    initialRefresh: false,
  );

  /// 成员变量
  int curPage = 1;
  int pageSize = 20;
  int total = 20;

  /// 事件

  void onRefresh() {
    fetchNewsList(isRefresh: true).then((_) {
      refreshController.refreshCompleted(resetFooterState: true);
    }).catchError((e) {
      refreshController.refreshFailed();
    });
  }

  void onLoading() {
    if (newsList.length < total) {
      fetchNewsList().then((_) {
        refreshController.loadComplete();
      }).catchError((_) {
        refreshController.loadFailed();
      });
    } else {
      refreshController.loadNoData();
    }
  }

  // 拉取数据
  Future<void> fetchNewsList({bool isRefresh = false}) async {
    var result = await HttpUtil().get('/product/getList', data: {
      "filterType": 4,
      "pageNumber": curPage,
      "pageSize": pageSize,
      "adminPermission": "mokeng666",
    });
    if (result['statusCode'] != "200") {
      toast(result['message']);
      return;
    }

    if (isRefresh == true) {
      curPage = 1;
      // total = result.counts!;
      newsList.clear();
    } else {
      curPage++;
    }

    newsList.addAll(result['result']);
  }

  /// 生命周期
  @override
  void onReady() {
    super.onReady();
    fetchNewsList(isRefresh: true);
  }

  ///dispose 释放内存
  @override
  void dispose() {
    super.dispose();
    // dispose 释放对象
    refreshController.dispose();
  }
}
